<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item label="原因" name="reason">
      <a-textarea v-model:value="formState.reason" />
    </a-form-item>
    <a-form-item label="类型" name="type">
      <a-input v-model:value="formState.type" />
    </a-form-item>
    <div class="flex justify-end">
      <a-button type="danger" @click="generate">自动生成</a-button>
    </div>
  </a-form>
</template>
<script lang="ts">
import { generateDeviceScrapForm } from "@/api/mock/cloud";
import { scrapDevice } from "@/controller/Cloud";
import { CloudDevice, CloudDeviceScrapForm } from "model";
import {
  defineComponent,
  inject,
  PropType,
  reactive,
  ref,
  toRaw,
  UnwrapRef,
} from "vue";
export default defineComponent({
  name: "DispatchCloudDeviceForm",
  props: {
    device: {
      type: Object as PropType<CloudDevice>,
      required: true,
    },
  },
  setup(props) {
    const refresh: Function = inject("refresh") ?? new Function();
    const formRef = ref();
    const formState: UnwrapRef<CloudDeviceScrapForm> = reactive({
      equipmentId: props.device.id,
      reason: "",
      type: "",
    });
    const rules = {
      reason: [
        {
          required: true,
          message: "请输入报废原因",
          trigger: "blur",
        },
      ],
      type: [
        {
          required: true,
          message: "请输入报废类型",
          trigger: "blur",
        },
      ],
    };
    const onSubmit = async (): Promise<boolean> => {
      return await formRef.value
        .validate()
        .then(async () => {
          await scrapDevice(toRaw(formState));
          Object.assign(formState, {
            reason: "",
            type: "",
          });
          refresh();
          return true;
        })
        .catch(() => {
          return false;
        });
    };
    const generate = () => {
      Object.assign(formState, generateDeviceScrapForm());
    };
    return {
      formRef,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      other: "",
      formState,
      rules,
      onSubmit,
      location,
      generate,
    };
  },
});
</script>
